<template>
  <div v-if="isOpen" class="fixed inset-0 z-50 flex items-center justify-center">
    <div class="absolute inset-0 bg-black opacity-50" @click="close"></div>
    <div class="bg-white dark:bg-gray-800 rounded-lg shadow-xl z-10 p-6 w-full max-w-md">
      <h2 class="text-xl font-bold mb-4 dark:text-white">邀请好友加入</h2>
      
      <div class="mb-4">
        <label for="invite-method" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">邀请方式</label>
        <div id="invite-method" class="flex space-x-4 mb-3">
          <button 
            @click="inviteMethod = 'friends'" 
            :class="[
              'px-3 py-1.5 rounded-md text-sm',
              inviteMethod === 'friends' 
                ? 'bg-indigo-600 text-white' 
                : 'bg-gray-200 text-gray-700 dark:bg-gray-700 dark:text-gray-300'
            ]"
          >
            从好友列表选择
          </button>
          <button 
            @click="inviteMethod = 'code'" 
            :class="[
              'px-3 py-1.5 rounded-md text-sm',
              inviteMethod === 'code' 
                ? 'bg-indigo-600 text-white' 
                : 'bg-gray-200 text-gray-700 dark:bg-gray-700 dark:text-gray-300'
            ]"
          >
            使用邀请码
          </button>
        </div>
      </div>
      
      <!-- 好友列表选择 -->
      <div v-if="inviteMethod === 'friends'" class="mb-4">
        <div v-if="isLoadingFriends" class="text-center py-4">
          <div class="animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-indigo-500 mx-auto"></div>
          <p class="mt-2 text-sm text-gray-500 dark:text-gray-400">加载好友列表...</p>
        </div>
        
        <div v-else-if="friends.length === 0" class="text-center py-4 text-gray-500 dark:text-gray-400">
          您还没有好友，无法邀请
        </div>
        
        <div v-else class="space-y-2 max-h-60 overflow-y-auto">
          <div 
            v-for="friend in friendsNotInGroup" 
            :key="friend._id"
            class="flex items-center justify-between p-2 rounded-md hover:bg-gray-100 dark:hover:bg-gray-700 cursor-pointer"
            @click="selectFriend(friend)"
          >
            <div class="flex items-center space-x-3">
              <div class="text-2xl">{{ friend.avatar }}</div>
              <div class="font-medium">{{ friend.username }}</div>
            </div>
            <div v-if="selectedFriends.includes(friend._id)" class="text-green-500">
              <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
                <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
              </svg>
            </div>
          </div>
        </div>
        
        <div v-if="friendsNotInGroup.length === 0 && friends.length > 0" class="text-center py-2 text-gray-500 dark:text-gray-400">
          所有好友都已经在群组中
        </div>
        
        <!-- 友好提示区域 -->
        <div v-if="selectedFriends.length > 0" class="mt-3 p-3 bg-blue-50 dark:bg-blue-900/20 rounded-md">
          <div class="flex items-start space-x-2">
            <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-blue-500 mt-0.5 flex-shrink-0" viewBox="0 0 20 20" fill="currentColor">
              <path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clip-rule="evenodd" />
            </svg>
            <div class="text-sm text-blue-700 dark:text-blue-300">
              <p class="font-medium">温馨提示</p>
              <p class="mt-1">如果好友之前已经收到过邀请，系统会提示您等待回应。每个好友只能有一个待处理的邀请。</p>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 邀请码方式 -->
      <div v-if="inviteMethod === 'code'" class="mb-4">
        <div v-if="isLoadingCode" class="text-center py-4">
          <div class="animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-indigo-500 mx-auto"></div>
          <p class="mt-2 text-sm text-gray-500 dark:text-gray-400">获取邀请码...</p>
        </div>
        
        <div v-else class="text-center">
          <p class="mb-2 text-sm text-gray-600 dark:text-gray-400">分享这个邀请码给您的朋友：</p>
          <div class="bg-gray-100 dark:bg-gray-700 p-3 rounded-md text-xl font-mono tracking-wider mb-3">
            {{ groupCode }}
          </div>
          <button 
            @click="copyGroupCode" 
            class="text-sm text-indigo-600 dark:text-indigo-400 hover:text-indigo-800 dark:hover:text-indigo-300"
          >
            点击复制
          </button>
          <div v-if="codeCopied" class="mt-2 text-sm text-green-500">
            已复制到剪贴板
          </div>
        </div>
      </div>
      
      <div class="flex justify-end space-x-3 mt-4">
        <button 
          type="button" 
          class="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md shadow-sm hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 dark:bg-gray-700 dark:text-gray-300 dark:border-gray-600 dark:hover:bg-gray-600"
          @click="close"
        >
          关闭
        </button>
        <button 
          v-if="inviteMethod === 'friends' && selectedFriends.length > 0"
          type="button" 
          class="px-4 py-2 text-sm font-medium text-white bg-indigo-600 border border-transparent rounded-md shadow-sm hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
          :disabled="isInviting"
          @click="sendInvitations"
        >
          {{ isInviting ? '邀请中...' : '发送邀请' }}
        </button>
      </div>
      
      <div v-if="error" class="mt-3">
        <!-- 重复邀请的友好提示 -->
        <div v-if="errorType === 'duplicate'" 
             class="p-3 bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-md">
          <div class="flex items-start space-x-2">
            <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-amber-500 mt-0.5 flex-shrink-0" viewBox="0 0 20 20" fill="currentColor">
              <path fill-rule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clip-rule="evenodd" />
            </svg>
            <div class="text-sm text-amber-700 dark:text-amber-300">
              <p class="font-medium">邀请状态提醒</p>
              <p class="mt-1">{{ error }}</p>
            </div>
          </div>
        </div>
        
        <!-- 其他错误的提示 -->
        <div v-else class="p-3 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-md">
          <div class="flex items-start space-x-2">
            <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-red-500 mt-0.5 flex-shrink-0" viewBox="0 0 20 20" fill="currentColor">
              <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clip-rule="evenodd" />
            </svg>
            <div class="text-sm text-red-700 dark:text-red-300">
              <p class="font-medium">发送失败</p>
              <p class="mt-1">{{ error }}</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue';
import { useToast } from 'vue-toastification';
import axios from 'axios';

export default {
  name: 'InviteToGroupModal',
  props: {
    isOpen: {
      type: Boolean,
      required: true
    },
    groupId: {
      type: String,
      required: true
    },
    groupName: {
      type: String,
      required: true
    }
  },
  emits: ['close'],
  setup(props, { emit }) {
    const toast = useToast();
    const inviteMethod = ref('friends');
    const selectedFriends = ref([]);
    const friends = ref([]);
    const groupMembers = ref([]);
    const isLoadingFriends = ref(false);
    const isLoadingCode = ref(false);
    const isInviting = ref(false);
    const error = ref('');
    const errorType = ref(''); // 'duplicate', 'failed', 'info'
    const groupCode = ref('');
    const codeCopied = ref(false);
    
    const friendsNotInGroup = computed(() => {
      const memberIds = groupMembers.value.map(member => member.user_id);
      return friends.value.filter(friend => !memberIds.includes(friend._id));
    });
    
    onMounted(() => {
      if (props.isOpen) {
        loadData();
      }
    });
    
    const loadData = async () => {
      if (inviteMethod.value === 'friends') {
        await loadFriends();
        await loadGroupMembers();
      } else if (inviteMethod.value === 'code') {
        await getGroupCode();
      }
    };
    
    const loadFriends = async () => {
      try {
        isLoadingFriends.value = true;
        const response = await axios.get('/api/users/friends');
        friends.value = response.data;
      } catch (err) {
        console.error('加载好友列表失败:', err);
        error.value = '无法加载好友列表';
        toast.error(error.value);
      } finally {
        isLoadingFriends.value = false;
      }
    };
    
    const loadGroupMembers = async () => {
      try {
        const response = await axios.get(`/api/groups/${props.groupId}`);
        groupMembers.value = response.data.members || [];
      } catch (err) {
        console.error('加载群组成员失败:', err);
      }
    };
    
    const getGroupCode = async () => {
      try {
        isLoadingCode.value = true;
        codeCopied.value = false;
        const response = await axios.get(`/api/groups/${props.groupId}`);
        groupCode.value = response.data.group_code || '无法获取邀请码';
      } catch (err) {
        console.error('获取群组邀请码失败:', err);
        error.value = '无法获取群组邀请码';
        toast.error(error.value);
      } finally {
        isLoadingCode.value = false;
      }
    };
    
    const selectFriend = (friend) => {
      const index = selectedFriends.value.indexOf(friend._id);
      if (index === -1) {
        selectedFriends.value.push(friend._id);
      } else {
        selectedFriends.value.splice(index, 1);
      }
    };
    
    const sendInvitations = async () => {
      if (selectedFriends.value.length === 0) return;
      
      try {
        isInviting.value = true;
        error.value = '';
        errorType.value = '';
        
        // 逐个发送邀请，以便处理可能的错误
        const results = await Promise.allSettled(
          selectedFriends.value.map(userId => 
            axios.post(`/api/groups/${props.groupId}/invite`, { userId })
          )
        );
        
        let successCount = 0;
        let failedCount = 0;
        let duplicateCount = 0;
        let otherErrors = [];
        
        // 分析发送结果
        for (let i = 0; i < results.length; i++) {
          const result = results[i];
          const userId = selectedFriends.value[i];
          const friend = friends.value.find(f => f._id === userId);
          const friendName = friend ? friend.username : '未知用户';
          
          if (result.status === 'fulfilled') {
            successCount++;
          } else {
            const errorMessage = result.reason?.response?.data?.message || result.reason?.message || '未知错误';
            
            if (errorMessage.includes('已经向该用户发送过邀请') || 
                errorMessage.includes('等待回应中')) {
              duplicateCount++;
            } else {
              failedCount++;
              otherErrors.push(`${friendName}: ${errorMessage}`);
            }
          }
        }
        
        // 根据结果显示不同的提示消息
        if (successCount > 0) {
          toast.success(`已成功发送 ${successCount} 个邀请`);
        }
        
        if (duplicateCount > 0) {
          toast.info(`${duplicateCount} 个好友已经收到过邀请，请耐心等待回应`, {
            timeout: 5000 // 显示5秒
          });
        }
        
        if (failedCount > 0) {
          const errorDetails = otherErrors.join('；');
          error.value = `${failedCount} 个邀请发送失败：${errorDetails}`;
          errorType.value = 'failed';
          toast.error(`${failedCount} 个邀请发送失败`);
        }
        
        // 如果有成功发送的邀请，清空选择并关闭模态框
        if (successCount > 0) {
          selectedFriends.value = [];
          emit('close');
        } else if (duplicateCount > 0 && failedCount === 0) {
          // 如果只是重复邀请，显示友好提示但不关闭模态框
          error.value = '选择的好友都已经收到过邀请，您可以选择其他好友或稍后再试';
          errorType.value = 'duplicate';
        }
        
      } catch (err) {
        console.error('发送邀请失败:', err);
        const errorMessage = err.response?.data?.message || '邀请发送失败，请稍后重试';
        
        // 特殊处理重复邀请的情况
        if (errorMessage.includes('已经向该用户发送过邀请') || 
            errorMessage.includes('等待回应中')) {
          error.value = '该好友已经收到过邀请，请耐心等待回应。您可以选择其他好友进行邀请。';
          errorType.value = 'duplicate';
          toast.info('该好友已收到邀请，请等待回应', { timeout: 4000 });
        } else {
          error.value = errorMessage;
          errorType.value = 'failed';
          toast.error(errorMessage);
        }
      } finally {
        isInviting.value = false;
      }
    };
    
    const copyGroupCode = () => {
      navigator.clipboard.writeText(groupCode.value).then(() => {
        codeCopied.value = true;
        setTimeout(() => {
          codeCopied.value = false;
        }, 2000);
      }).catch(() => {
        toast.error('无法复制到剪贴板');
      });
    };
    
    const close = () => {
      selectedFriends.value = [];
      error.value = '';
      errorType.value = '';
      codeCopied.value = false;
      emit('close');
    };
    
    return {
      inviteMethod,
      friends,
      friendsNotInGroup,
      selectedFriends,
      isLoadingFriends,
      isLoadingCode,
      isInviting,
      error,
      errorType,
      groupCode,
      codeCopied,
      selectFriend,
      sendInvitations,
      copyGroupCode,
      close,
      loadData
    };
  },
  watch: {
    isOpen(val) {
      if (val) {
        this.loadData();
      }
    },
    inviteMethod() {
      this.loadData();
    }
  }
};
</script> 